package com.graduation.smartparkingplatform.Utils;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Alipay {

  @Value("${aliPay.publicKey")
  private String publicKey;

  @Value("${aliPay.client.serverUrl}")
  private String Url;

  @Value("${aliPay.client.appId}")
  private String Id;

  @Value("${aliPay.client.privateKey}")
  private String Key;

  @Value("${aliPay.client.returnUrl}")
  private String rUrl;

  @Value("${aliPay.client.notifyUrl}")
  private String nUrl;
  /**
   * 支付接口
   *
   * @param alipayBean
   * @return
   * @throws AlipayApiException
   */
  public String pay(AlipayBean alipayBean) throws AlipayApiException {
    // 1、获得初始化的AlipayClient
    String serverUrl = Url;
    String appId = Id;
    String privateKey = Key;
    String format = "json";
    String charset = "UTF-8";
    String alipayPublicKey = publicKey;
    String signType = "RSA2";
    String returnUrl = rUrl; // 支付成功跳转页面
    String notifyUrl = nUrl;
    AlipayClient alipayClient =
        new DefaultAlipayClient(
            serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
    // 2、设置请求参数
    AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
    // 页面跳转同步通知页面路径
    alipayRequest.setReturnUrl(returnUrl);
    // 服务器异步通知页面路径
    alipayRequest.setNotifyUrl(notifyUrl);
    // 封装参数
    alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
    // 3、请求支付宝进行付款，并获取支付结果
    String result = alipayClient.pageExecute(alipayRequest).getBody();
    // 返回付款信息
    return result;
  }
}
